package com.yida.gwj.deposit.service.impl;

import com.yida.common.core.exception.ServiceException;
import com.yida.common.core.text.Convert;
import com.yida.common.core.utils.DateUtils;
import com.yida.common.core.utils.StringUtils;
import com.yida.common.security.utils.SecurityUtils;
import com.yida.gwj.common.constant.GwjRemarkConstants;
import com.yida.gwj.common.domain.dto.GwjUserDTO;
import com.yida.gwj.common.enums.GwjBusinessLogResult;
import com.yida.gwj.deposit.domain.GwjDepositBusiness;
import com.yida.gwj.deposit.domain.GwjDepositBusinessLog;
import com.yida.gwj.deposit.mapper.GwjDepositBusinessLogMapper;
import com.yida.gwj.deposit.service.IGwjDepositBusinessLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 签署意见（缴存业务管理模块）Service业务层处理
 *
 * @author lqq
 * @date 2023-01-09
 */
@Service
public class GwjDepositBusinessLogServiceImpl implements IGwjDepositBusinessLogService {
	@Autowired
	private GwjDepositBusinessLogMapper gwjDepositBusinessLogMapper;

	/**
	 * 查询签署意见（缴存业务管理模块）
	 *
	 * @param bizLogId 签署意见（缴存业务管理模块）主键
	 * @return 签署意见（缴存业务管理模块）
	 */
	@Override
	public GwjDepositBusinessLog selectGwjDepositBusinessLogByBizLogId(Long bizLogId) {
		return gwjDepositBusinessLogMapper.selectGwjDepositBusinessLogByBizLogId(bizLogId);
	}

	/**
	 * 查询签署意见（缴存业务管理模块）列表
	 *
	 * @param gwjDepositBusinessLog 签署意见（缴存业务管理模块）
	 * @return 签署意见（缴存业务管理模块）
	 */
	@Override
	public List<GwjDepositBusinessLog> selectGwjDepositBusinessLogList(GwjDepositBusinessLog gwjDepositBusinessLog) {
		return gwjDepositBusinessLogMapper.selectGwjDepositBusinessLogList(gwjDepositBusinessLog);
	}

	/**
	 * 新增签署意见（缴存业务管理模块）
	 *
	 * @param gwjDepositBusinessLog 签署意见（缴存业务管理模块）
	 * @return 结果
	 */
	@Override
	public int insertGwjDepositBusinessLog(GwjDepositBusinessLog gwjDepositBusinessLog) {
		gwjDepositBusinessLog.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getRealName());
		gwjDepositBusinessLog.setCreateTime(DateUtils.getNowDate());
		return gwjDepositBusinessLogMapper.insertGwjDepositBusinessLog(gwjDepositBusinessLog);
	}

	/**
	 * 修改签署意见（缴存业务管理模块）
	 *
	 * @param gwjDepositBusinessLog 签署意见（缴存业务管理模块）
	 * @return 结果
	 */
	@Override
	public int updateGwjDepositBusinessLog(GwjDepositBusinessLog gwjDepositBusinessLog) {
		gwjDepositBusinessLog.setUpdateBy(SecurityUtils.getLoginUser().getSysUser().getRealName());
		gwjDepositBusinessLog.setUpdateTime(DateUtils.getNowDate());
		return gwjDepositBusinessLogMapper.updateGwjDepositBusinessLog(gwjDepositBusinessLog);
	}

	/**
	 * 批量删除签署意见（缴存业务管理模块）
	 *
	 * @param bizLogIds 需要删除的签署意见（缴存业务管理模块）主键
	 * @return 结果
	 */
	@Override
	public int deleteGwjDepositBusinessLogByBizLogIds(Long[] bizLogIds) {
		return gwjDepositBusinessLogMapper.deleteGwjDepositBusinessLogByBizLogIds(bizLogIds);
	}

	/**
	 * 删除签署意见（缴存业务管理模块）信息
	 *
	 * @param bizLogId 签署意见（缴存业务管理模块）主键
	 * @return 结果
	 */
	@Override
	public int deleteGwjDepositBusinessLogByBizLogId(Long bizLogId) {
		return gwjDepositBusinessLogMapper.deleteGwjDepositBusinessLogByBizLogId(bizLogId);
	}

	/**
	 * 根据步业务ID删除日志
	 *
	 * @param bizId 业务ID
	 * @return 操作者ID
	 */
	@Override
	public int deleteGwjDepositBusinessLogByBizId(Long bizId) {
		return gwjDepositBusinessLogMapper.deleteGwjDepositBusinessLogByBizId(bizId);
	}

	/**
	 * 根据步骤查询的终提交人
	 *
	 * @param bizId  业务ID
	 * @param stepId 步骤ID
	 * @return 操作者ID
	 */
	@Override
	public GwjUserDTO getPreviousSubmitUser(Long bizId, Long stepId) {
		return gwjDepositBusinessLogMapper.selectPreviousSubmitUser(bizId, stepId, GwjBusinessLogResult.SUBMIT.getCode());
	}

	/**
	 * 送件日志
	 *
	 * @param gwjDepositBusinessLog 业务日志
	 * @param gwjDepositBusiness    业务信息
	 */
	@Override
	public void addSendLog(GwjDepositBusinessLog gwjDepositBusinessLog, GwjDepositBusiness gwjDepositBusiness) {
		Long currentUserId = SecurityUtils.getUserId();
		gwjDepositBusinessLog.setStepId(gwjDepositBusiness.getStepId());
		gwjDepositBusinessLog.setOperId(currentUserId);
		gwjDepositBusinessLog.setOperName(gwjDepositBusiness.getCurrentOperName());
		gwjDepositBusinessLog.setEndTime(new Date());
		//获取上一次流程的最后时间
		gwjDepositBusinessLog.setAcceptTime(gwjDepositBusinessLogMapper.selectPreviousEndDateByBizId(gwjDepositBusiness.getBizId()));
		gwjDepositBusinessLog.setContent("送件");
		gwjDepositBusinessLog.setResult(GwjBusinessLogResult.SEND.getCode());
		gwjDepositBusinessLog.setRemark(
				GwjRemarkConstants.SEND_BUSINESS.replace("{username}", SecurityUtils.getLoginUser().getSysUser().getRealName())
						.replace("{userId}", Convert.toStr(currentUserId))
						.replace("{username1}", gwjDepositBusinessLog.getRealName())
						.replace("{userId1}", Convert.toStr(gwjDepositBusinessLog.getUserId()))
						.replace("{businessId}", Convert.toStr(gwjDepositBusiness.getBizId()))
		);
		if (1 != insertGwjDepositBusinessLog(gwjDepositBusinessLog)) {
			throw new ServiceException("新增送件日志失败");
		}
	}

	/**
	 * 签署意见日志
	 *
	 * @param gwjDepositBusinessLog 日志信息
	 */
	@Override
	public void addSignOpinionLog(GwjDepositBusinessLog gwjDepositBusinessLog) {
		Long currentUserId = SecurityUtils.getUserId();
		String currentUser = SecurityUtils.getLoginUser().getSysUser().getRealName();
		gwjDepositBusinessLog.setOperId(currentUserId);
		gwjDepositBusinessLog.setOperName(currentUser);
		gwjDepositBusinessLog.setEndTime(new Date());
		//获取上一次流程的最后时间
		gwjDepositBusinessLog.setAcceptTime(gwjDepositBusinessLogMapper.selectPreviousEndDateByBizId(gwjDepositBusinessLog.getBizId()));
		gwjDepositBusinessLog.setResult(GwjBusinessLogResult.SAVE.getCode());
		gwjDepositBusinessLog.setRemark(
				GwjRemarkConstants.SIGN_OPINION.replace("{username}", currentUser)
						.replace("{userId}", Convert.toStr(currentUserId))
						.replace("{content}", gwjDepositBusinessLog.getContent())
						.replace("{businessId}", Convert.toStr(gwjDepositBusinessLog.getBizId()))
		);
		if (1 != insertGwjDepositBusinessLog(gwjDepositBusinessLog)) {
			throw new ServiceException("新增签署意见日志失败");
		}
	}

	/**
	 * 回退日志
	 *
	 * @param gwjDepositBusinessLog 业务信息
	 */
	@Override
	public void addFallbackLog(GwjDepositBusinessLog gwjDepositBusinessLog) {
		Long currentUserId = SecurityUtils.getUserId();
		String currentUser = SecurityUtils.getLoginUser().getSysUser().getRealName();
		gwjDepositBusinessLog.setOperId(currentUserId);
		gwjDepositBusinessLog.setOperName(currentUser);
		gwjDepositBusinessLog.setEndTime(new Date());
		//获取上一次流程的最后时间
		gwjDepositBusinessLog.setAcceptTime(gwjDepositBusinessLogMapper.selectPreviousEndDateByBizId(gwjDepositBusinessLog.getBizId()));
		if (StringUtils.isBlank(gwjDepositBusinessLog.getContent())) {
			gwjDepositBusinessLog.setContent("回退");
		}
		gwjDepositBusinessLog.setResult(GwjBusinessLogResult.FALLBACK.getCode());
		gwjDepositBusinessLog.setRemark(
				GwjRemarkConstants.FALLBACK.replace("{username}", currentUser)
						.replace("{userId}", Convert.toStr(currentUserId))
						.replace("{username1}", gwjDepositBusinessLog.getRealName())
						.replace("{userId1}", Convert.toStr(gwjDepositBusinessLog.getUserId()))
						.replace("{businessId}", Convert.toStr(gwjDepositBusinessLog.getBizId()))
		);
		if (1 != insertGwjDepositBusinessLog(gwjDepositBusinessLog)) {
			throw new ServiceException("新增回退日志失败");
		}
	}

	/**
	 * 保存日志
	 *
	 * @param gwjDepositBusiness 业务信息
	 */
	@Override
	public void addSaveLog(GwjDepositBusiness gwjDepositBusiness) {
		Long currentUserId = SecurityUtils.getUserId();
		String currentUser = SecurityUtils.getLoginUser().getSysUser().getRealName();
		GwjDepositBusinessLog gwjDepositBusinessLog = new GwjDepositBusinessLog();
		gwjDepositBusinessLog.setBizId(gwjDepositBusiness.getBizId());
		Date previousEndDate = gwjDepositBusinessLogMapper.selectPreviousEndDateByBizId(gwjDepositBusinessLog.getBizId());
		gwjDepositBusinessLog.setAcceptTime(StringUtils.isNull(previousEndDate) ? gwjDepositBusiness.getApplicantTime() : previousEndDate);
		gwjDepositBusinessLog.setEndTime(new Date());
		gwjDepositBusinessLog.setStepId(gwjDepositBusiness.getStepId());
		gwjDepositBusinessLog.setOperId(currentUserId);
		gwjDepositBusinessLog.setOperName(currentUser);
		gwjDepositBusinessLog.setResult(GwjBusinessLogResult.SAVE.getCode());
		gwjDepositBusinessLog.setRemark(
				GwjRemarkConstants.SAVE.replace("{username}", currentUser)
						.replace("{userId}", Convert.toStr(currentUserId))
						.replace("{businessId}", Convert.toStr(gwjDepositBusiness.getBizId()))
		);
		if (1 != insertGwjDepositBusinessLog(gwjDepositBusinessLog)) {
			throw new ServiceException("新增保存日志失败");
		}
	}

	/**
	 * 提交日志
	 *
	 * @param gwjDepositBusinessLog 业务日志
	 * @param gwjDepositBusiness    业务信息
	 */
	@Override
	public void addSubmitLog(GwjDepositBusinessLog gwjDepositBusinessLog, GwjDepositBusiness gwjDepositBusiness) {
		gwjDepositBusinessLog.setAcceptTime(gwjDepositBusinessLogMapper.selectPreviousEndDateByBizId(gwjDepositBusiness.getBizId()));
		gwjDepositBusinessLog.setOperId(SecurityUtils.getUserId());
		gwjDepositBusinessLog.setOperName(SecurityUtils.getLoginUser().getSysUser().getRealName());
		gwjDepositBusinessLog.setEndTime(new Date());
		gwjDepositBusinessLog.setResult(GwjBusinessLogResult.SUBMIT.getCode());
		if (StringUtils.isAnyBlank(gwjDepositBusinessLog.getRealName(), Convert.toStr(gwjDepositBusinessLog.getUserId()))) {
			gwjDepositBusinessLog.setRemark(GwjRemarkConstants.SUBMIT_NOBODY.replace("{username}", SecurityUtils.getLoginUser().getSysUser().getRealName())
					.replace("{userId}", Convert.toStr(SecurityUtils.getUserId()))
					.replace("{businessId}", Convert.toStr(gwjDepositBusiness.getBizId())));
		} else {
			gwjDepositBusinessLog.setRemark(GwjRemarkConstants.SUBMIT.replace("{username}", SecurityUtils.getLoginUser().getSysUser().getRealName())
					.replace("{userId}", Convert.toStr(SecurityUtils.getUserId()))
					.replace("{username1}", gwjDepositBusinessLog.getRealName())
					.replace("{userId1}", Convert.toStr(gwjDepositBusinessLog.getUserId()))
					.replace("{businessId}", Convert.toStr(gwjDepositBusinessLog.getBizId())));
		}
		if (1 != insertGwjDepositBusinessLog(gwjDepositBusinessLog)) {
			throw new ServiceException("新增提交日志失败");
		}
	}

	/**
	 * 完结日志
	 *
	 * @param gwjDepositBusiness 业务信息
	 */
	@Override
	public void addFinishLog(GwjDepositBusiness gwjDepositBusiness) {
		GwjDepositBusinessLog gwjDepositBusinessLog = new GwjDepositBusinessLog();
		gwjDepositBusinessLog.setBizId(gwjDepositBusiness.getBizId());
		Date data = new Date();
		gwjDepositBusinessLog.setAcceptTime(data);
		gwjDepositBusinessLog.setEndTime(data);
		gwjDepositBusinessLog.setStepId(gwjDepositBusiness.getStepId());
		gwjDepositBusinessLog.setOperId(gwjDepositBusiness.getCurrentOperId());
		gwjDepositBusinessLog.setOperName(gwjDepositBusiness.getCurrentOperName());
		gwjDepositBusinessLog.setResult(GwjBusinessLogResult.FINISH.getCode());
		if (1 != insertGwjDepositBusinessLog(gwjDepositBusinessLog)) {
			throw new ServiceException("新增完结日志失败");
		}
	}

	/**
	 * 业务作废日志
	 *
	 * @param gwjDepositBusinessLog 业务信息
	 */
	@Override
	public void addInvalidBusinessLog(GwjDepositBusinessLog gwjDepositBusinessLog) {
		Long currentUserId = SecurityUtils.getUserId();
		String currentUser = SecurityUtils.getLoginUser().getSysUser().getRealName();
		gwjDepositBusinessLog.setAcceptTime(gwjDepositBusinessLogMapper.selectPreviousEndDateByBizId(gwjDepositBusinessLog.getBizId()));
		gwjDepositBusinessLog.setOperId(currentUserId);
		gwjDepositBusinessLog.setOperName(currentUser);
		gwjDepositBusinessLog.setEndTime(new Date());
		gwjDepositBusinessLog.setResult(GwjBusinessLogResult.INVALID.getCode());
		gwjDepositBusinessLog.setRemark(
				GwjRemarkConstants.INVALID.replace("{username}", currentUser)
						.replace("{userId}", Convert.toStr(currentUserId))
						.replace("{businessId}", Convert.toStr(gwjDepositBusinessLog.getBizId()))
		);
		if (1 != insertGwjDepositBusinessLog(gwjDepositBusinessLog)) {
			throw new ServiceException("新增业务作废日志失败");
		}
	}

	/**
	 * 查询签署意见（缴存业务管理模块）
	 *
	 * @param bizId 业务ID
	 * @return 签署意见（缴存业务管理模块）
	 */
	@Override
	public List<GwjDepositBusinessLog> selectGwjDepositBusinessLogListByBizId(Long bizId) {
		GwjDepositBusinessLog businessLog = new GwjDepositBusinessLog();
		businessLog.setBizId(bizId);
		List<GwjDepositBusinessLog> logs = gwjDepositBusinessLogMapper.selectGwjDepositBusinessLogList(businessLog);
		return logs.stream().sorted(Comparator.comparing(GwjDepositBusinessLog::getAcceptTime).reversed()).collect(Collectors.toList());
	}
}
